$(() => {
    $('.btn').on('click', function () {
        let url = wurl + '/user/login';
        let mobile = $('.mobile').val();
        if (!/^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/.test(mobile)) {
            layer.msg('手机号格式错误');
            return false;
        }
        let password = $('.password').val();
        $.post(url, { mobile, password }, function (response) {
            if (response.code != 0) {
                layer.msg(response.msg);
                return false;
            }
            if ($('.chb').prop("checked")) {
                $.cookie('user', response.data, { expires: 7, path: '/' });
            } else {
                $.cookie('user', response.data, { path: '/' });
            }
            let userId = response.data.id;
            // 登录完成后，需要对登录前的购物车转移到数据库中
            let userCart = localStorage.getItem('userCart') ? JSON.parse(localStorage.getItem('userCart')) : {};
            if (Object.keys(userCart).length > 0) {
                $.get(wurl + '/cart/lists', { userId }, response => {
                    response.data.forEach(item => {
                        if (item.goodsId in userCart) {
                            userCart[item.goodsId] += item.goodsCount;
                        }
                    });

                    let data = {
                        carts: [],
                        userId
                    }
                    
                    for (let key in userCart) {
                        data.carts.push({ goodsId: key, goodsCount: userCart[key] });
                    }
                    $.ajax({
                        url: wurl + '/cart/addAll',
                        type: 'post',
                        contentType: 'application/json',
                        data: JSON.stringify(data),
                        success: response => {
                            localStorage.removeItem('userCart');
                            // 跳转情况
                            let backUrl = getUrlParam('back') ? decodeURIComponent(getUrlParam('back')) : 'index.html';
                            location.href = backUrl;
                        }
                    });
                });
            }else{
                location.href = 'index.html';
            }
        });
    })
});

